package com.mti.app.view
{
	import com.mti.app.ApplicationFacade;
	import com.mti.app.view.mycomponents.SettingsView;
	import com.mti.epivisite.common.event.EpivisiteEvent;
	import com.mti.epivisite.common.event.EventProxy;
	import com.mti.epivisite.common.event.EventProxyBase;
	
	import flash.events.MouseEvent;
	
	import media.MediaPicture;
	import media.MediaPoint;
	import media.MediaText;
	
	import mx.collections.ArrayCollection;
	import mx.controls.Alert;
	import mx.events.CloseEvent;
	import mx.events.IndexChangedEvent;
	import mx.events.ValidationResultEvent;
	
	import org.puremvc.as3.interfaces.IMediator;
	import org.puremvc.as3.interfaces.INotification;
	import org.puremvc.as3.patterns.mediator.Mediator;
	
	public class ApplicationMediator extends Mediator implements IMediator
	{
		public static const NAME:String = "ApplicationMediator";
		
		[Bindable]
		public var serverEvent:EventProxy = null;
		
		public function ApplicationMediator(viewComponent:EpiVisiteBureautique)
		{
			super(NAME, viewComponent);
		}
		
		private function get app():EpiVisiteBureautique
		{
			return viewComponent as EpiVisiteBureautique;
		}
		
		override public function onRegister():void
		{
			super.onRegister();
			
			serverEvent = new EventProxy();
			
			facade.registerMediator(new QRCodeViewMediator(app.qrcodeView));
			facade.registerMediator(new EvenementViewMediator(app.evenementView));
			
			app.loginView.loginButton.addEventListener(MouseEvent.CLICK, loginButtonClickHandler);
			app.loginView.createButton.addEventListener(MouseEvent.CLICK, createButtonClickHandler);
			
			app.saveButton.addEventListener(MouseEvent.CLICK, saveButtonClickHandler);
			app.cancelButton.addEventListener(MouseEvent.CLICK, cancelButtonClickHandler);
			app.closeButton.addEventListener(MouseEvent.CLICK, closeButtonClickHandler);
			
			app.tabNavigator.addEventListener(IndexChangedEvent.CHANGE, tabNavigatorChangeHandler);
			
			app.settingsView.submitPasswordButton.addEventListener(MouseEvent.CLICK, submitPasswordButtonClickHandler);
			app.settingsView.deleteButton.addEventListener(MouseEvent.CLICK, deleteButtonClickHandler);
			
			app.dataContext = this;
		}
		
		override public function listNotificationInterests():Array
		{
			return [
				EventProxyBase.LOAD_SUCCESS,
				EventProxyBase.LOAD_ERROR,
				EventProxyBase.SAVE_SUCCESS,
				EventProxyBase.SAVE_ERROR,
				EventProxyBase.GET_POINTS_SUCCESS
			];
		}
		
		override public function handleNotification(note:INotification):void
		{
			switch (note.getName())
			{	
				case EventProxyBase.LOAD_SUCCESS:
					eventLoadSuccessHandler();
					break;
				
				case EventProxyBase.LOAD_ERROR:
					resetLoginView();
					app.loginView.loginForm.errorString = note.getBody() as String;
					break;
				
				case EventProxyBase.SAVE_SUCCESS:
					sendNotification(ApplicationFacade.COMMAND_LOAD_QRCODE);
					sendNotification(ApplicationFacade.VIEW_QRCODE);
					resetLoginView();
					app.currentState = EpiVisiteBureautique.STATE_LOGGED;
					break;
				
				case EventProxyBase.SAVE_ERROR:
					resetLoginView();
					app.loginView.createForm.errorString = note.getBody() as String;									
					break;
				
				case EventProxyBase.GET_POINTS_SUCCESS:
					initRoute();
					break;
			}
		}
		
		public function loginButtonClickHandler(event:MouseEvent):void
		{
			if ((app.loginView.loginNameValidator.validate().type == ValidationResultEvent.VALID)
				&& (app.loginView.loginPasswordValidator.validate().type == ValidationResultEvent.VALID))
			{
				app.loginView.currentState = "LoginLoading";
				serverEvent.load(app.loginView.loginNameInput.text);
			}
			
		}

		public function eventLoadSuccessHandler():void
		{
			var event:EpivisiteEvent = serverEvent.baseEvent;
			var password:String = app.loginView.loginPasswordInput.text;
			
			if ((event != null) && (password == event.password))
			{
				app.currentState = EpiVisiteBureautique.STATE_LOGGED;
				resetLoginView();
				
				sendNotification(ApplicationFacade.COMMAND_LOAD_QRCODE);
			}
			else
			{
				resetLoginView();
				app.loginView.loginForm.errorString = "Mot de passe incorrect";
			}
		}
		
		private var baseRoute:ArrayCollection = null;
		
		private function initRoute():void
		{
			var event:EpivisiteEvent = serverEvent.modifiedEvent;
			var route:ArrayCollection = new ArrayCollection();
			var point:MediaPoint = null;
			
			for each (point in event.pointList)
			{
				if (point.name == "wp")
				{
					route.addItem(point);
				}
			}
			for each (point in route)
			{
				event.pointList.removeItemAt(event.pointList.getItemIndex(point));
			}
			
			baseRoute = route;
			var eventMediator:EvenementViewMediator = facade.retrieveMediator(EvenementViewMediator.NAME) as EvenementViewMediator;
			eventMediator.route = route;
			eventMediator.drawRoute();
		}
		
		public function createButtonClickHandler(event:MouseEvent):void
		{
			if ((app.loginView.createNameValidator.validate().type == ValidationResultEvent.VALID)
				&& (app.loginView.createPasswordValidator.validate().type == ValidationResultEvent.VALID)
				&& (app.loginView.createConfirmValidator.validate().type == ValidationResultEvent.VALID))
			{
				if (app.loginView.createPasswordInput.text != app.loginView.createConfirmInput.text)
				{
					app.loginView.createForm.errorString = "Les mots de passe sont différents.";										
				}
				else
				{
					app.loginView.currentState = "CreateLoading";
					var e:EpivisiteEvent = new EpivisiteEvent();
					e.name = app.loginView.createNameInput.text;
					e.title = e.name;
					e.password = app.loginView.createPasswordInput.text;
					e.mapPath = null;
					e.description = e.name;
					e.startDate = new Date();
					e.endDate = new Date();
					serverEvent.save(e);
					serverEvent.baseEvent = e;;
					serverEvent.modifiedEvent = e;
				}
			}
		}
		
		private function resetLoginView():void
		{
			app.loginView.currentState = "Normal";
			
			app.loginView.loginNameValidator.enabled = false;
			app.loginView.loginPasswordValidator.enabled = false;
			app.loginView.createNameValidator.enabled = false;
			app.loginView.createPasswordValidator.enabled = false;
			app.loginView.createConfirmValidator.enabled = false;
			
			app.loginView.loginPasswordInput.text = "";
			app.loginView.createPasswordInput.text = "";
			app.loginView.createConfirmInput.text = "";
			
			app.loginView.loginNameInput.errorString = "";
			app.loginView.loginPasswordInput.errorString = "";
			app.loginView.createNameInput.errorString = "";
			app.loginView.createPasswordInput.errorString = "";
			app.loginView.createConfirmInput.errorString = "";
			
			app.loginView.loginForm.errorString = "";
			app.loginView.createForm.errorString = "";
			
			app.loginView.loginNameValidator.enabled = true;
			app.loginView.loginPasswordValidator.enabled = true;
			app.loginView.createNameValidator.enabled = true;
			app.loginView.createPasswordValidator.enabled = true;
			app.loginView.createConfirmValidator.enabled = true;
		}
		
		private function saveButtonClickHandler(event:MouseEvent):void
		{
			var savedEvent:EpivisiteEvent = serverEvent.modifiedEvent;
			var point:MediaPoint = null;
			
			serverEvent.updateTitle(savedEvent, savedEvent.title);
			serverEvent.updateDescription(savedEvent, savedEvent.description);
			serverEvent.updateStartDate(savedEvent, savedEvent.startDate);
			serverEvent.updateEndDate(savedEvent, savedEvent.endDate);
			//ApplicationMediator.serverEvent.updateMap(evenement, (ByteArray (this.evenementView.fieldImage.source)));
			
			var eventMediator:EvenementViewMediator = facade.retrieveMediator(EvenementViewMediator.NAME) as EvenementViewMediator;
			eventMediator.stopCreatingRoute();
			savedEvent.pointList.addAll(eventMediator.route);
			
			for each (point in savedEvent.pointList)
			{
				if (point.Visited == true)
				{
					serverEvent.addPoint(point, savedEvent);
					point.Visited = false;
				}
				else
				{
					serverEvent.updatePointDescription(savedEvent, point);
					serverEvent.updatePointPositionX(savedEvent, point);
					serverEvent.updatePointPositionY(savedEvent, point);
					for each (var pic:MediaPicture in point.pictureList)
					{
						serverEvent.addPicture(savedEvent, pic, pic.imageData);
					}
					for each (var txt:MediaText in point.textList)
					{
						serverEvent.addText(savedEvent, txt);
					}
				}
			}
			
			if (eventMediator.route != baseRoute)
			{
				savedEvent.deletedPointList.addAll(baseRoute);
			}
			for each (point in savedEvent.deletedPointList)
			{
				serverEvent.deletePoint(savedEvent, point.name);
			}
			savedEvent.deletedPointList.removeAll();
			baseRoute = eventMediator.route;
			
			serverEvent.baseEvent = savedEvent.Copy();
		}
		
		private function cancelButtonClickHandler(event:MouseEvent):void
		{
			serverEvent.modifiedEvent = serverEvent.baseEvent.Copy();
			
			var eventMediator:EvenementViewMediator = facade.retrieveMediator(EvenementViewMediator.NAME) as EvenementViewMediator;
			eventMediator.stopCreatingRoute();
			initRoute();
		}
		
		private function closeButtonClickHandler(event:MouseEvent):void
		{
			app.currentState = EpiVisiteBureautique.STATE_LOGIN;
		}
		
		private function tabNavigatorChangeHandler(event:IndexChangedEvent):void
		{
			app.settingsView.currentState = SettingsView.STATE_NORMAL;
		}
		
		private function submitPasswordButtonClickHandler(event:MouseEvent):void
		{
			var password:String = app.settingsView.passwordInput.text;
			
			if (password != app.settingsView.confirmInput.text)
			{
				app.settingsView.currentState = SettingsView.STATE_ERROR;
				app.settingsView.message = "Les mots de passe sont différents.";
			}
			else
			{
				app.settingsView.currentState = SettingsView.STATE_SUCCESS;
				app.settingsView.message = "Changement de mot de passe réussi !";
				serverEvent.baseEvent.password = password;
				serverEvent.modifiedEvent.password = password;
				serverEvent.updatePassword(serverEvent.modifiedEvent, password);
			}
			app.settingsView.passwordInput.text = "";
			app.settingsView.confirmInput.text = "";
		}
		
		private function deleteButtonClickHandler(event:MouseEvent):void
		{
			Alert.yesLabel = "Supprimer";
			Alert.cancelLabel = "Annuler";
			
			var alertMessage:String = "Supprimer l'évènement " + serverEvent.baseEvent.name + " ? Cette action est définitive.";
				
			Alert.show(alertMessage, "Suppression", Alert.YES | Alert.CANCEL, app, deleteAlertHandler, Icons.Warning);
			
			Alert.yesLabel = "Yes";
			Alert.cancelLabel = "Cancel";
		}
		
		private function deleteAlertHandler(event:CloseEvent):void
		{
			if (event.detail == Alert.YES)
			{
				serverEvent.deleteEvent(serverEvent.baseEvent);
				app.currentState = EpiVisiteBureautique.STATE_LOGIN;
			}
		}
	}
}